package com.ptswitch.material.pages.material;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.hxzon.project.AppRuntimeException;
import org.hxzon.tapestry5.model.ValueLabel;
import org.hxzon.util.EMailUtil.EMail;
import org.slf4j.Logger;

import com.ptswitch.material.model.common.EMailAddress;
import com.ptswitch.material.model.material.Material;
import com.ptswitch.material.model.material.MaterialAttachment;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.EMailAddressService;
import com.ptswitch.material.service.MaterialAttachmentService;
import com.ptswitch.material.service.MaterialService;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.MaterialUtil;
import com.ptswitch.material.util.ValueLabelUtil;
import com.ptswitch.material.util.WebUtil;
import com.ptswitch.material.util.security.PermissionCheckUtil;
import com.ptswitch.material.util.security.PermissionUtil;

public class CreateMaterial extends PageBase {
    @Environmental
    private JavaScriptSupport _jsSupport;
    @Inject
    private PageRenderLinkSource _pageRenderLinkSource;
    @InjectPage
    private ViewMaterial viewMaterial;
    @Inject
    private Logger logger;
    @Inject
    private MaterialService materialSer;
    @Inject
    private MaterialAttachmentService uploadSer;
    @Inject
    private EMailAddressService emailAddressSer;
    //
    @Property
    private List<UploadedFile> files;
    @Property
    private Material material;
    @Property
    private EMail email;
    @Property
    private List<EMailAddress> emailAddresses;
    @Property
    private ValueLabel<EMailAddress> emailAddressLabel;
    //
    @Property
    private boolean isNewPcbDecal = false;
    @Property
    private boolean materialMoreButton = false;
    @Property
    private boolean emailMoreButton = false;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init() {
        checkPermitted(PermissionCheckUtil.permittedAny(PermissionUtil.MaterialCreate));
        files = new ArrayList<UploadedFile>();
        material = new Material();
        email = MaterialUtil.newEMail();
        emailAddresses = emailAddressSer.findAll();
        emailAddressLabel = ValueLabelUtil.emailAddressLabel;
        return null;
    }

    @BeginRender
    void beginRender(MarkupWriter writer) {
        Link link = _pageRenderLinkSource.createPageRenderLink(EmptyCode.class);
        _jsSupport.addScript("jq(function() {\n"//
                + "jq('button#emptyCode').click(function() {\n"//
                + "var data = jq('input#m_code').val();\n"//
                + "if (data.length <= 0) {\n"//
                + "jq.messager.alert('请先输入编码前缀，例如A1，Z9','');\n"//
                + "return false;\n"//
                + "}\n"//
                + "var url = '%s/' + data;\n"//
                + "jq.post(url, function(data) {\n"//
                + "jq('input#m_code').val(data);\n"//
                + "});\n"//
                + "return false;\n"//
                + "});//reg\n"//
                + "});\n"//
        , link.toURI());
    }

    @OnEvent(value = EventConstants.VALIDATE, component = "add")
    Object checkMaterial() {
        logger.trace("check material");
        checkPermitted(PermissionCheckUtil.permittedAny(PermissionUtil.MaterialCreate));
        // check code empty,never happen
        if (material.getCode() == null || material.getCode().isEmpty()) {
            throw AppRuntimeException.error("保存物料失败：物料编码不能为空");
        }
        //check code exist
        if (materialSer.findByCode(material.getCode()) != null) {
            throw AppRuntimeException.error("保存物料失败：物料编码已经存在");
        }
        // check is new pcb decal
        String pcbDecal = material.getPcbDecal();
        if (isNewPcbDecal && materialSer.existPcbDecal(pcbDecal)) {
            throw AppRuntimeException.error("保存物料失败：物料的PCB封装不是新封装");
        }
        if (!isNewPcbDecal && !materialSer.existPcbDecal(pcbDecal)) {
            throw AppRuntimeException.error("保存物料失败：物料的PCB封装不存在");
        }
        return null;
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "add")
    Object add() {
        logger.trace("success");
        // save
        materialSer.save(material);
        //for upload
        List<MaterialAttachment> uploads = WebUtil.upload(files, MaterialAttachment.class);
        for (MaterialAttachment upload : uploads) {
            upload.setOwnerId(material.getId());
            uploadSer.save(upload);
            hlog(HlogConstants.addUpload, upload);
        }
        // send mail
        for (EMailAddress address : emailAddresses) {
            email.addTo(address.getEmail());
        }
        email.setSubject(getVisitor().getRealname() + HlogConstants.addMaterial);
        email.addText(email.getTmpTextContent());
        email.addHtml(MaterialUtil.linkForViewMaterial(getWebUrl(), material));
        email.addText(MaterialUtil.buildMessage(material));
        sendEMail(email);
        // hlog
        hlog(HlogConstants.addMaterial, material);
        return viewMaterial.withInit(material.getId());
    }

}
